package com.ruoyi.framework.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//@Configuration
public class RabbitMqConfig {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMqConfig.class);

    //@Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory)
    {
        logger.info("rabbitMq init--------------");
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //消息发送成功的回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            logger.info("RabbitMqConfig ConfirmCallback:     "+"消息唯一标识："+correlationData.getId());
            logger.info("RabbitMqConfig ConfirmCallback:     "+"是否发送成功："+ack);
            logger.info("RabbitMqConfigConfirmCallback:     "+"原因："+cause);
        });
        //发生异常时的消息返回提醒
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {

                    logger.info("RabbitMqConfig ReturnCallback  返回消息回调:{} 应答代码:{} 回复文本:{} 交换器:{} 路由键:{}", returnedMessage.getMessage(), returnedMessage.getReplyCode(), returnedMessage.getReplyText(), returnedMessage.getExchange(), returnedMessage.getRoutingKey());
            }
        });
        return rabbitTemplate;
    }

    @Bean
    public Queue messageQueue()
    {
        /**
         * name:消息队列的名称
         * durable:是否需要持久化数据
         */
        return new Queue("messageQueue",true);
    }
    /*@Bean
    public Queue messageQueue1()
    {
        return new Queue("messageQueue1");
    }*/

    @Bean
    public DirectExchange messageDirectExchange()
    {
        /**
         * durable:表示是否持久化数据，默认就是开启的，可不设置
         */
        return new DirectExchange("messageDirectExchange",true,false);
    }

    @Bean
    Binding bindingDirect()
    {
        /**
         * routingKey:当多个queue绑定相同的exchange时，我们发送消息要想发到具体的队列中就需要带上routingKey
         * 当多个队列的routingKey相同，那么消息就会同时发送到多个队列中
         */
        return BindingBuilder.bind(messageQueue()).to(messageDirectExchange()).with("testRoutingKey");
    }

 /*   @Bean
    Binding bindingDirect1()
    {
        return BindingBuilder.bind(messageQueue1()).to(messageDirectExchange()).with("testRoutingKey");
    }*/
}
